var app = getApp().globalData;

var md5 = require("./md5.js");

import { store } from "@/store/index.js";

function uploadVideo(data, callback) {
	var that = this;
	//当前上传的哪张图片
	//上传成功的个数
	var formData = data.formData;
	var needSign = data.needSign === false ? false : true;
	var requestUrl; //请求地址

	var userInfo = uni.getStorageSync('userInfo');
	console.log(getApp().globalData.XcxData)
	formData.merchant_id = getApp().globalData.XcxData.merchant_id; //商户id

	if (userInfo.uid && needSign) {
		formData.uid = userInfo.uid; //用户id
	}

	if ((formData.store_id === '' || formData.store_id === undefined || formData.store_id === null) && store.store_id) {
		formData.store_id = store.store_id; //门店id
	}

	var openid = getApp().globalData.XcxData.openid;

	if (openid) {
		formData.openid = openid; //用户openid
	}
	// #ifdef MP-WEIXIN
	formData.original_type = 1;
	// #endif
	// #ifdef MP-ALIPAY
	formData.original_type = 2;
	// #endif

	requestUrl = getApp().globalData.XcxData.domain + data.url;

	if (getApp().globalData.XcxData.systemInfo && getApp().globalData.XcxData.systemInfo.model) {
		formData.equip = getApp().globalData.XcxData.systemInfo.model;
	}

	var key = uni.getStorageSync('signKey');

	if (key && needSign) {
		let keysSorted = Object.keys(formData).sort(); //排序健名

		var signArr = {};

		for (let j = 0; j < keysSorted.length; j++) {
			signArr[keysSorted[j]] = formData[keysSorted[j]];
		}

		formData = signArr;
	}

	var postData = formData;
	formData = getApp().globalData.modifyPostParam(formData);
	console.log(formData);

	if (key && needSign) {
		var str = formData + '&key=' + key;
		var str = decodeURIComponent(str);
		var sign = md5.md5(str);
		postData.sign = sign;
		formData += '&sign=' + sign;
	}
	uni.uploadFile({
		url: requestUrl,
		filePath: data.path,
		name: data.name,
		fileType: data.fileType,
		//这里根据自己的实际情况改
		formData: postData,
		//这里是上传视频时一起上传的数据
		method: "POST",
		success: resp => {
			console.log(1, resp);
			let imgobj = JSON.parse(resp.data);
			uni.showToast({
				title: '上传成功',
				icon: 'success'
			});
			callback(imgobj)
		},
		fail: res => {
			console.log(2, res)
			uni.showToast({
				title: res.errMsg,
				icon: 'none'
			});
			uni.hideLoading()
		},
	});
}

module.exports = {
	uploadVideo: uploadVideo
};
